package org.example.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 锁的模板类
 * @author shenguangyang
 */
public abstract class LockTemplate implements MyLock {
    private static final Logger log = LoggerFactory.getLogger(LockTemplate.class);
    protected int macTryLockCount = 5;
    @Override
    public void lock() {
        int tryCount = macTryLockCount;
        while (tryCount-- > 0) {
            if (tryLock()) {
                return;
            } else {
                // 等待释放锁
                waitLock();
            }
            log.warn("try get lock, tryCount: {}", macTryLockCount - tryCount);
        }
        if (tryCount <= 0) {
            unlock();
            throw new RuntimeException("get lock fail");
        }
    }

    /**
     * 尝试加锁
     */
    protected abstract boolean tryLock();

    /**
     * 等待锁被释放
     */
    protected abstract void waitLock();
}
